<template>
  <section class="owner-billTable">
    <a-tabs v-model:activeKey="activeTabKey" size="small" @change="onTabChange">
      <a-tab-pane key="payment" tab="收款账单" />
      <a-tab-pane key="collection" tab="付款账单" />
      <template #rightExtra>
        <a-range-picker
          v-model:value="dateRange"
          class="range-picker"
          @change="onRangeChange"
          :ranges="{
            今天: [moment(), moment()],
            昨天: [moment().subtract(1, 'days'),moment()],
            本周: [moment().startOf('week'), moment().endOf('week')],
            本月: [moment().startOf('month'), moment().endOf('month')],
          }"
          allowClear
        />
      </template>
    </a-tabs>

    <a-table
      :dataSource="dataList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      rowKey="id"
      @change="handleTableChange"
      :customRow="customRow"
      :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'room_info'">
          <div v-if="text && text.split(',').length > 3">
            <a-popover overlayClassName="room-popover">
              <template #content>
                <div class="room-popover-content">
                  {{text}}
                </div>
              </template>
              <div class="theretext">
                {{text}}
              </div>
            </a-popover>
          </div>
          <div v-else>{{text || '--'}}</div>
        </template>
        <template v-if="column.key === 'actual_payment'">
          <span v-if="text">{{ text }}</span>
          <span v-else>0</span>
        </template>
        <template v-if="column.key === 'timeout_status'">
          <span v-if="text == 0">正常</span>
          <span v-else style="color: #ff3141">逾期</span>
        </template>
        <template v-if="column.key === 'settle_status'">
          <span v-if="text == 2" style="color: #87d068">{{
            record.settle_status_txt
          }}</span>
          <span v-else style="color: #108ee9">{{
            record.settle_status_txt
          }}</span>
        </template>
        <template v-if="column.key === 'tax_rate'">
          <span v-if="text">{{ text }}</span>
          <span v-else>0</span>
        </template>
        <template v-if="column.key === 'tax_amount'">
          <span v-if="text">{{ text }}</span>
          <span v-else>0</span>
        </template>
      </template>
    </a-table>

    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="billDetailId"
      @cancel="
        () => {
          billDetailVisible = false;
        }
      "
    />
  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  toRefs,
  watch,
  computed,
  defineAsyncComponent,
} from "vue";
import { useRouter } from "vue-router";
import request from "../../../common/utils/request";
import moment from "moment";
import { message } from "ant-design-vue";
const BillDetailDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);

export default defineComponent({
  name: "ownerBillTable",
  props: {
    id: Number,
  },
  components: {
    BillDetailDrawer,
  },
  setup(props, context) {
    const $router = useRouter();
    const billDetailVisible = ref(false);
    const billDetailId = ref(0);

    const loading = ref(false);
    const activeTabKey = ref("payment");
    const dateRange = ref([]);
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const bill_type = ref(1);
    const timeoutStatusList = ref([]);
    const settleStatusList = ref([]);
    const selectedTimeoutStatusList = ref([]);
    const selectedSettleStatusList = ref([]);
    const dataList = ref([]);

    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    watch(
      [
        page,
        limit,
        bill_type,
        dateRange,
        selectedTimeoutStatusList,
        selectedSettleStatusList,
      ],
      (
        [
        page,
        limit,
        bill_type,
        dateRange,
        selectedTimeoutStatusList,
        selectedSettleStatusList
        ]
      ) => {
        if(!selectedSettleStatusList.length){
          return
        }
        getContractTableData();
      }
    );

    watch(
      () => props.id,
      (val) => {
        init();
      }
    );

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      selectedTimeoutStatusList.value = filters.timeout_status;
      if(filters?.settle_status?.length){
        selectedSettleStatusList.value = filters.settle_status;
      }
      if (filters.settle_status==null) {
        message.warn('请至少选择一个')
        selectedSettleStatusList.value=[]
      }
    };

    const getStatusList = () => {
      request
        .get("/org", "/bill/listSearchInit ", {})
        .then((res) => {
          console.log("11111111111111", res.data);
          timeoutStatusList.value = res.data.timeoutStatus;
          settleStatusList.value = res.data.settleStatus;
          if (res.data.settleStatus && res.data.settleStatus.length > 0) {
            res.data.settleStatus.map((item) => {
              if (item.key != 2) {
                selectedSettleStatusList.value.push(item.key.toString());
              }
            });
          }
        })
        .finally(() => {
          getContractTableData();
        });
    };

    const getContractTableData = () => {
      loading.value = true;
      request
        .post("/org", "/owner/billList", {
          page: page.value,
          limit: limit.value,
          id: props.id,
          bill_type: bill_type.value,
          start_time:
            dateRange.value?.length > 0
              ? moment(dateRange.value[0]).format("YYYY-MM-DD")
              : "",
          end_time:
            dateRange.value?.length > 0
              ? moment(dateRange.value[1]).format("YYYY-MM-DD")
              : "",
          timeout_status: selectedTimeoutStatusList.value || [],
          settle_status: selectedSettleStatusList.value,
        })
        .then((res) => {
          loaded = true;
          console.log("------------------", res);
          dataList.value = res.list;
          total.value = res.total;
        })
        .finally(() => {
          loading.value = false;
        });
    };

    const init = () => {
      getStatusList();
    };

    init();

    const columns = computed(() => {
      return [
        {
          title: "费用类型",
          dataIndex: "cost_type_txt",
          width: 120,
        },
        {
          title: "账单金额",
          dataIndex: "bill_amount",
          width: 120,
        },
        {
          title: "应收金额",
          dataIndex: "receivable_payment",
          width: 120,
        },
        {
          title: "实收金额",
          dataIndex: "actual_payment",
          key: "actual_payment",
          width: 120,
        },
        {
          title: "需收金额",
          dataIndex: "receivable_payment",
          width: 120,
        },
        {
          title: "楼宇名称",
          dataIndex: "build_name",
          width: 120,
        },
        {
          title: "楼号/房号",
          dataIndex: "room_info",
          key:'room_info',
          width: 120,
        },
        {
          title: "应收日期",
          dataIndex: "receivable_payment_date",
          width: 120,
        },
        {
          title: "税率",
          dataIndex: "tax_rate",
          key: "tax_rate",
          width: 100,
        },
        {
          title: "税额",
          dataIndex: "tax_amount",
          key: "tax_amount",
          width: 100,
        },
        {
          title: "逾期状态",
          dataIndex: "timeout_status",
          key: "timeout_status",
          filters:
            timeoutStatusList.value && timeoutStatusList.value.length
              ? timeoutStatusList.value.map((item) => ({
                  value: item.key.toString(),
                  text: item.name,
                }))
              : [],
          filterMultiple: true,
          defaultFilteredValue: selectedTimeoutStatusList.value,
          width: 120,
        },
        {
          title: "结清状态",
          dataIndex: "settle_status",
          key: "settle_status",
          filters:
            settleStatusList.value && settleStatusList.value.length
              ? settleStatusList.value.map((item) => ({
                  value: item.key.toString(),
                  text: item.name,
                }))
              : [],
          filterMultiple: true,
          defaultFilteredValue: selectedSettleStatusList.value,
          width: 120,
        },
      ];
    });

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      if (record.id) {
        billDetailId.value = record.id;
        billDetailVisible.value = true;
      }
    };

    const onTabChange = (params) => {
      page.value = 1;
      console.log(params);
      if (params == "payment") {
        bill_type.value = 1;
      } else {
        bill_type.value = 2;
      }
    };

    const onRangeChange = (dates, dateString) => {
      page.value = 1;
      console.log(dates, dateString,'dates, dateString');
    };

    let loaded = false;
    watch(
      () => props.active,
      (val) => {
        if (val && !loaded) {
          //   getTableData();
        }
      }
    );

    return {
      loading,
      activeTabKey,
      dateRange,
      page,
      limit,
      total,
      dataList,
      columns,
      customRow,
      onTabChange,
      pagination,
      handleTableChange,
      moment,
      onRangeChange,
      billDetailVisible,
      billDetailId,
    };
  },
});
</script>

<style lang="less" scoped>
.owner-billTable {
  :deep(.ant-tabs) {
    background-color: #fff;
    padding: 10px;
  }
  :deep(.ant-tabs-bar) {
    margin-bottom: 0;
  }
  :deep(.ant-input) {
    padding: 0;
  }

  .theretext{
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3; //行数需设置
      line-clamp: 3;
      -webkit-box-orient: vertical;
  }
}
.room-popover{
  .room-popover-content{
    width: 200px; 
    max-height: 200px; 
    overflow: hidden auto
  }
}
</style>
